package image

import (
	"code.google.com/p/graphics-go/graphics"
	"image"
	// "image/bmp"
	"image/gif"
	"image/jpeg"
	"image/png"
	"os"
	// "strings"
)

// const (
// 	path     = "2.png"
// 	savepath = "x.jpg"
// 	width    = 160
// 	height   = 220
// )

func Thumbnail(path, savepath string, width, height int) error {
	var dst *image.RGBA
	// imgtype := strings.Split(path, ".")[1]
	dx := 0
	dy := 0
	file, err2 := os.Open(path)
	if err2 != nil {
		return err2
	}
	defer file.Close()
	img, _, err := image.Decode(file)
	if err != nil {
		img, err = png.Decode(file)
		if err != nil {
			img, err = jpeg.Decode(file)
			if err != nil {
				img, err = gif.Decode(file)
				if err != nil {
					return err
				}
			}
		}
	}

	x := img.Bounds().Dx()
	y := img.Bounds().Dy()
	if width != 0 {
		dx = width
		dy = width * y / x
	}
	if height != 0 && dy != 0 && height < dy {
		dx = height * dx / dy
		dy = height
	} else if dy == 0 {
		dx = height * x / y
		dy = height
	}
	if err != nil {
		return err
	}
	if x < dx || y < dy {
		return nil
	}

	dst = image.NewRGBA(image.Rect(0, 0, dx, dy))
	err = graphics.Thumbnail(dst, img)
	if err != nil {
		return err
	}

	f3, err := os.Create(savepath)
	if err != nil {
		return err
	}
	// png.Encode(f3, dst)
	jpeg.Encode(f3, dst, &jpeg.Options{90})
	return nil
}
